const WebSocket = require("ws");
const utils = require("../utils/util");
const util = new utils;
// const UserModel = require("../model/user");
const {saveMessage} =require("../controllers/message.controller")
const { TOKEN_ENCODE_STR, URL_YES_PASS } = require("../utils/config");
const jwt = require("jsonwebtoken");
const wss = new WebSocket.Server({
  port: 3009
});
module.exports.listen = async () => {
  wss.on("connection", (ws, req) => {
    ws.on("message", async (msg) => {
      const data = JSON.parse(msg);
      console.log(data, "服务端接受数据");
      const token = req.url.split("?token=")[1];
      const { str = "" } = await jwt.verify(token, TOKEN_ENCODE_STR);

      const uid = str;
      console.log(uid, "12");
      if (util.search(userList, uid)) {
        userList.push(uid);
        console.log(userList, uid);
      }
      //添加好友
      if (data.check == 9) {
        await saveMessage(data.data);
        Array.from(wss.clients).forEach((value, index) => {
          Array.from(wss.clients)[index].send(JSON.stringify({
            "user_id": "接收到了接受好友消息",
            "check": index,
            "user_num": userList
          }));
        });
      }
      ws.on("close", () => {
        util.remove(userList, uid); //退出从列表中删除
        wss.clients.forEach(function each(client) {
          client.send(JSON.stringify({
            "user_id": uid,
            "check": "1",
            "user_num": `${userList.length}`
          }));
        });
      });
    });
  });
};
// Array.from(wss.clients).forEach((value, index) => {
//   let id = userList.indexOf(find.id);
//   console.log(index, "--");
//   if (id !== index) {
//     Array.from(wss.clients)[index].send(JSON.stringify({
//       "user_id": "接收到了接受好友消息",
//       "check": index,
//       "user_num": userList
//     }));
//   }
// });
